package GUILayer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.*;

import CtrLayer.CtrBeneficiaryPayment;
import CtrLayer.CtrContract;
import CtrLayer.CtrRentalPayment;
import ModelLayer.BeneficiaryPayment;
import ModelLayer.DateHelper;
import ModelLayer.RentalPayment;

import javax.swing.LayoutStyle.ComponentPlacement;

public class PaymentGUI extends DateHelper {
	CtrRentalPayment ctrRentalPay;
	CtrBeneficiaryPayment ctrBenPay;
	CtrContract ctrContract;
	
	JPanel mainPanel;
	

	public PaymentGUI() {
		super();
		ctrRentalPay = new CtrRentalPayment();
		ctrBenPay = new CtrBeneficiaryPayment();
		ctrContract = new CtrContract();
		
		initComponents();
	}
	

	public JPanel getPanel() {
		return mainPanel;
	}
	
	
	public void setError(String error){
		MainWindow.setError(error);
	}
	
	
	


	
	// RENTAL table vars
	JTextField searchRentalField;
	JTextField specificRentalSearch;
	JTable tableRentalPay;
	String[] tableRentalHeader   = new String[] { "ID", "Date", "Amount", "Apartment", "Tenant"};
	String[] rentalAttr    = new String[] {"paymentId", "date", "amount", "rp.apartId",   "tenantId"};
	
	ArrayList<String> searchRentalArr = new ArrayList<>();
	JScrollPane scrollRentalPay = new JScrollPane();
	
	JPanel tableRentalPanel = new JPanel();
	JPanel searchRentalPanel = new JPanel();
	
	JPanel specificSearchRentalPanel;
	JPanel specificSearchOptionsRentalPanel;
	
	
	// Beneficiary table vars
	JTextField searchBenField;
	JTextField specificBenSearch;
	JTable tableBenPay;
	String[] tableBenHeader = new String[] { "ID", "Date", "Amount", "Type",  "Apartment No","Building"};
	String[] benAttr  = new String[] {"paymentId", "date", "amount", "type",  "bp.apartId",  "ap.buildingNr"};
	
	ArrayList<String> searchBenArr = new ArrayList<>();
	JScrollPane scrollBenPay = new JScrollPane();
	
	JPanel tableBenPanel = new JPanel();
	JPanel searchBenPanel = new JPanel();
	
	JPanel specificSearchBenPanel;
	JPanel specificSearchOptionsBenPanel;
	
	
	
	String[] signs = new String[] {"=", "\u2265", "\u2264"};
	
	
	
	
	
	public static boolean isNumeric(String str)
	{
	    for (char c : str.toCharArray())
	    {
	        if (!Character.isDigit(c)) return false;
	    }
	    return true;
	}
	
	
	
	
	
	
	// Beneficiary methods
	private boolean addSearchBenOption(String finalSearch){
		
		if(searchBenArr.contains(finalSearch) || searchBenArr.size()>15)
		{
			setError("You have reached the limit of 14 simulataneous beneficiary payments searches");
			return false;
		}
		
		searchBenArr.add(finalSearch);
		makeTabelBen();
		
		return true;
	}
	
	private void removeSearchBenOption(String finalSearch){
		searchBenArr.remove(finalSearch);
		makeTabelBen();
	}
	
	
	private String getSearchBenOptions(){
		String searchALL = "";
		
		for(int i=0;i<searchBenArr.size()-1;i++) searchALL += searchBenArr.get(i) + " AND ";
		
		if(!searchBenArr.isEmpty()) searchALL += searchBenArr.get(searchBenArr.size()-1);
		
		return searchALL;
	}
	
	
	
	
	private void makeTabelBen(){
		makeTabelBen(ctrBenPay.getAll_where(getSearchBenOptions()));
	}
	
	private boolean searchedBen;
	private void makeTabelBen(String searchF){
		
		if(!searchF.isEmpty())
		{
			searchedBen = true;
			makeTabelBen(ctrBenPay.searchRandom(searchF));
		}
		else if(searchedBen)
		{
			searchedBen = false;
			makeTabelBen();
		}
	}
	
	
	
	ArrayList<BeneficiaryPayment> benPays;
	
	private void makeTabelBen(ArrayList<BeneficiaryPayment> benPay){
		
		tableBenPay = new JTable();
		tableBenPay.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		benPays = benPay; 
		double totalAmount=0;
		
		Object[][] tableContent = new Object[benPay.size()][tableBenHeader.length];
		
		int i=0;
		for(BeneficiaryPayment bp : benPays)
		{
			int j=0;
			tableContent[i][j++] = bp.getPaymentId();
			tableContent[i][j++] = bp.getDateTimeFormated();
			tableContent[i][j++] = bp.getAmount();
			tableContent[i][j++] = bp.getType();
			tableContent[i][j++] = bp.getApartment().getApartNo();
			tableContent[i][j++] = bp.getApartment().getBuilding().getBuildingName();
			
			totalAmount += bp.getAmount();
			i++;
		}
		
		
		tableBenPay.setModel(new DefaultTableModel(tableContent, tableBenHeader) {
			private static final long serialVersionUID = 1L;
			
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		});
		
		tableBenPay.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		tableBenPay.setAutoCreateRowSorter(true);
		
		
		scrollBenPay.setViewportView(tableBenPay);
		scrollBenPay.validate();
		scrollBenPay.repaint();
		
		ffTotalAmount.setText(""+totalAmount);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	// Rental methods
	private boolean addSearchRentalOption(String finalSearch){
		
		if(searchRentalArr.contains(finalSearch) || searchRentalArr.size()>15)
		{
			setError("You have reached the limit of 14 simulataneous rental payments searches");
			return false;
		}
		
		searchRentalArr.add(finalSearch);
		makeTabelRental();
		
		return true;
	}
	
	private void removeSearchRentalOption(String finalSearch){
		searchRentalArr.remove(finalSearch);
		makeTabelRental();
	}
	
	
	private String getSearchRentalOptions(){
		String searchALL = "";
		
		for(int i=0;i<searchRentalArr.size()-1;i++) searchALL += searchRentalArr.get(i) + " AND ";
		
		if(!searchRentalArr.isEmpty()) searchALL += searchRentalArr.get(searchRentalArr.size()-1);
		
		return searchALL;
	}
	
	
	
	
	
	private void makeTabelRental(){
		makeTabelRental(ctrRentalPay.getAll_where(getSearchRentalOptions()));
	}
	
	private boolean searchedRental;
	private void makeTabelRental(String searchF){
		
		if(!searchF.isEmpty())
		{
			searchedRental = true;
			makeTabelRental(ctrRentalPay.searchRandom(searchF));
		}
		else if(searchedRental)
		{
			searchedRental = false;
			makeTabelRental();
		}
	}
	
	
	
	ArrayList<RentalPayment> rentalPay;
	
	List<Object[]> failedPayments = new ArrayList<>();
	
	private void makeTabelRental(ArrayList<RentalPayment> rentPay)
	{
		
		tableRentalPay = new JTable();
		tableRentalPay.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableRentalPay.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		
		rentalPay = rentPay; 
		
		final Object[][] tableContent = new Object[rentPay.size()+failedPayments.size()][tableRentalHeader.length];
		
		int i=0;
		
		for(Object[] obj : failedPayments)
		{
			int j=0;
			tableContent[i][j] = obj[j++];
			tableContent[i][j] = obj[j++];
			tableContent[i][j] = obj[j++];
			tableContent[i][j] = obj[j++];
			tableContent[i][j] = obj[j++];
			i++;
		}
		
		
		for(RentalPayment rp : rentalPay)
		{
			int j=0;
			tableContent[i][j++] = rp.getPaymentId();
			tableContent[i][j++] = rp.getDateFormated();
			tableContent[i][j++] = rp.getAmount();
			tableContent[i][j++] = rp.getApartment().getApartNo()+" "+rp.getApartment().getBuilding().getBuildingName();
			tableContent[i][j++] = rp.getTenant().getName();
			i++;
		}
		
		
		

		Action action = new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e)
		    {
		        TableCellListener tcl = (TableCellListener)e.getSource();
		        
		        int apId = 0;
		        
		        if(tcl.getColumn()==4)	//if edit Tenant
		        {
		        	try{
		        		int newTenantId = Integer.parseInt((String)tcl.getNewValue());
		        		apId = ctrContract.getContract_byTenantId(newTenantId).getApartment().getApartId();
		        	}
		        	catch(Exception ex){
		        		String newTenantName = (String)tcl.getNewValue();
		        		apId = ctrContract.getContract_byTenantName(newTenantName).getApartment().getApartId();
		        	}
		        	
		        	tableRentalPay.setValueAt(apId,tcl.getRow(),3);
		        }
		        else 
		        	apId = Integer.parseInt((String)tcl.getNewValue());
			    
		        if(apId > 0)
		        {
		        	if(addPayment((double)failedPayments.get(tcl.getRow())[2], apId, (Timestamp)failedPayments.get(tcl.getRow())[1], false))
		        	{
		        		failedPayments.remove(tcl.getRow());
		        		makeTabelRental();
		        	}
		        }
		    }
		};

		
		new TableCellListener(tableRentalPay, action);
		
		
		
		
		tableRentalPay.setModel(new DefaultTableModel(tableContent, tableRentalHeader) {
			private static final long serialVersionUID = 1L;
			
			public boolean isCellEditable(int row, int col) {
				return (row < failedPayments.size()  && (col==3 || col==4));
			}
		});
		
		tableRentalPay.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
		{
			private static final long serialVersionUID = 1L;

			@Override
		    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
		    {
		        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
		        c.setBackground(row < failedPayments.size() ? new Color(255,135,135) : Color.WHITE);
		        return c;
		    }
		});
		

		
		if(failedPayments.size()>0) 
			tableRentalPay.setAutoCreateRowSorter(false);
		else
			tableRentalPay.setAutoCreateRowSorter(true);
		
		
		
		scrollRentalPay.setViewportView(tableRentalPay);
		scrollRentalPay.validate();
		scrollRentalPay.repaint();
	}
	
	
	


	

	
	
	
	private void initComponents_Rental() {
		
		makeTabelRental();
		
		tableRentalPanel.setLayout(new GridLayout(0, 1, 0, 0));
		tableRentalPanel.add(scrollRentalPay);
		
		scrollRentalPay.setAlignmentY(Component.TOP_ALIGNMENT);
		scrollRentalPay.getHorizontalScrollBar().setPreferredSize(new Dimension(0,12));
		scrollRentalPay.getVerticalScrollBar().setPreferredSize(new Dimension(13,0));
		
		
		
		// ======== searchRentalPanel ========
		JPanel generalSearchRentalPanel;
		final JComboBox<String> comboBoxRentalAttr = new JComboBox<>();
		final JComboBox<String> comboBoxSign = new JComboBox<>();
		JPanel comboBoxPanel;
		
		
		specificSearchOptionsRentalPanel = new JPanel();
		specificSearchOptionsRentalPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		
		searchRentalField = new JSearchTextField(new IFSearch() {
			public void submit() {
				String searchString = searchRentalField.getText();
				makeTabelRental(searchString);
			}
		});
		searchRentalField.setColumns(7);
		
		
		
		
		specificRentalSearch = new JSearchTextField(new IFSearch() {
			public void submit() {
				String searchString = specificRentalSearch.getText();
				if(!searchString.isEmpty())
				{
					
					int attr = comboBoxRentalAttr.getSelectedIndex();
					int sign = comboBoxSign.getSelectedIndex();
					
					
					String signS = "=";
					String extra = "";
					String searchAttr = rentalAttr[attr];
					
					if(!isNumeric(searchString) && !searchString.equals("true") && !searchString.equals("false"))   // if search by varchar
					{
						searchString = "'%"+searchString+"%'";
						signS = " LIKE ";
						
						if(attr==4) searchAttr = "p.fname";
					}
					else if(sign==1) signS = ">=";
					else if(sign==2) signS = "<=";
					
					if(attr == 4)
						extra = " OR p.lname"+signS+searchString;
					else if(attr == 3)
						extra = " OR ap.apartNo"+signS+searchString;
					
					
					final String finalSearch = "("+searchAttr+signS+searchString+extra+")";
					
					
					if(!addSearchRentalOption(finalSearch)) return;	// the search already exists
					
					
					String comboAttr = (String)comboBoxRentalAttr.getSelectedItem();
					Object comboSign = comboBoxSign.getSelectedItem();
					
					
					final JButton searchOptionBtn = new JButton(comboAttr+comboSign+specificRentalSearch.getText());
					searchOptionBtn.setToolTipText("Click to remove");
					searchOptionBtn.setBackground(new Color(241, 102, 106));
					
					
					searchOptionBtn.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							removeSearchRentalOption(finalSearch);
							specificSearchOptionsRentalPanel.remove(searchOptionBtn);
							specificSearchOptionsRentalPanel.validate();
							specificSearchOptionsRentalPanel.repaint();
						}
					});
					
					specificSearchOptionsRentalPanel.add(searchOptionBtn);
					specificSearchOptionsRentalPanel.validate();
					specificSearchOptionsRentalPanel.repaint();
				}
			}
		});
		specificRentalSearch.setColumns(5);
		
		
		
		
		generalSearchRentalPanel = new JPanel();
		generalSearchRentalPanel.setBorder(new MatteBorder(0, 0, 1, 0, (Color) new Color(0, 0, 0)));
		generalSearchRentalPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		generalSearchRentalPanel.add(searchRentalField);
		
		
		comboBoxRentalAttr.setModel(new DefaultComboBoxModel<String>(tableRentalHeader));
		comboBoxSign.setModel(new DefaultComboBoxModel<String>(signs));
		
		
		comboBoxPanel = new JPanel();
		comboBoxPanel.setBorder(new EmptyBorder(0, 0, 12, 0));
		comboBoxPanel.add(comboBoxRentalAttr);
		comboBoxPanel.add(comboBoxSign);		
		comboBoxPanel.add(specificRentalSearch);
		
		

		JScrollPane comboBoxScroll = new JScrollPane(comboBoxPanel);
		comboBoxScroll.setBorder(null);
		comboBoxScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
		comboBoxScroll.getHorizontalScrollBar().setPreferredSize(new Dimension(0,14));
		
		
		specificSearchRentalPanel = new JPanel();
		specificSearchRentalPanel.setLayout(new BorderLayout(0, 0));
		specificSearchRentalPanel.add(comboBoxScroll, BorderLayout.NORTH);
		specificSearchRentalPanel.add(specificSearchOptionsRentalPanel, BorderLayout.CENTER);
		
		
		searchRentalPanel.setLayout(new BorderLayout(0, 0));
		searchRentalPanel.add(generalSearchRentalPanel, BorderLayout.NORTH);
		searchRentalPanel.add(specificSearchRentalPanel, BorderLayout.CENTER);
		searchRentalPanel.setBorder(new LineBorder(Color.black));
	}
	
	
	
	
	
	
	
	
	
	
	
	private void initComponents_Ben() {
		
		makeTabelBen();
		
		tableBenPanel.setLayout(new GridLayout(0, 1, 0, 0));
		tableBenPanel.add(scrollBenPay);
		
		scrollBenPay.setAlignmentY(Component.TOP_ALIGNMENT);
		scrollBenPay.getHorizontalScrollBar().setPreferredSize(new Dimension(0,12));
		scrollBenPay.getVerticalScrollBar().setPreferredSize(new Dimension(13,0));
		
		
		// ======== searchBenPanel ========
		JPanel generalSearchBenPanel;
		final JComboBox<String> comboBoxBenAttr = new JComboBox<>();
		final JComboBox<String> comboBoxSign = new JComboBox<>();
		JPanel comboBoxPanel;
		
		
		specificSearchOptionsBenPanel = new JPanel();
		specificSearchOptionsBenPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		
		searchBenField = new JSearchTextField(new IFSearch() {
			public void submit() {
				String searchString = searchBenField.getText();
				makeTabelBen(searchString);
			}
		});
		searchBenField.setColumns(7);
		
		
		
		
		specificBenSearch = new JSearchTextField(new IFSearch() {
			public void submit() {
				String searchString = specificBenSearch.getText();
				if(!searchString.isEmpty())
				{
					
					int attr = comboBoxBenAttr.getSelectedIndex();
					int sign = comboBoxSign.getSelectedIndex();
					
					
					String signS = "=";
					String extra = "";
					String searchAttr = benAttr[attr];
					
					if(!isNumeric(searchString) && !searchString.equals("true") && !searchString.equals("false"))   // if search by varchar
					{
						searchString = "'%"+searchString+"%'";
						signS = " LIKE ";
						
						if(attr==5) searchAttr = "b.buildingName";
					}
					else if(sign==1) signS = ">=";
					else if(sign==2) signS = "<=";
					
					if(attr == 4)
						extra = " OR ap.apartNo"+signS+searchString;
					
					
					final String finalSearch = "("+searchAttr+signS+searchString+extra+")";
					
					
					if(!addSearchBenOption(finalSearch)) return;	// the search already exists
					
					
					String comboAttr = (String)comboBoxBenAttr.getSelectedItem();
					Object comboSign = comboBoxSign.getSelectedItem();
					
					
					final JButton searchOptionBtn = new JButton(comboAttr+comboSign+specificBenSearch.getText());
					searchOptionBtn.setToolTipText("Click to remove");
					searchOptionBtn.setBackground(new Color(241, 102, 106));
					
					
					searchOptionBtn.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							removeSearchBenOption(finalSearch);
							specificSearchOptionsBenPanel.remove(searchOptionBtn);
							specificSearchOptionsBenPanel.validate();
							specificSearchOptionsBenPanel.repaint();
						}
					});
					
					specificSearchOptionsBenPanel.add(searchOptionBtn);
					specificSearchOptionsBenPanel.validate();
					specificSearchOptionsBenPanel.repaint();
				}
			}
		});
		specificBenSearch.setColumns(5);
		
		
		
		
		generalSearchBenPanel = new JPanel();
		generalSearchBenPanel.setBorder(new MatteBorder(0, 0, 1, 0, (Color) new Color(0, 0, 0)));
		generalSearchBenPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		generalSearchBenPanel.add(searchBenField);
		
		
		comboBoxBenAttr.setModel(new DefaultComboBoxModel<String>(tableBenHeader));
		comboBoxSign.setModel(new DefaultComboBoxModel<String>(signs));
		
		
		comboBoxPanel = new JPanel();
		comboBoxPanel.setBorder(new EmptyBorder(0, 0, 12, 0));
		comboBoxPanel.add(comboBoxBenAttr);
		comboBoxPanel.add(comboBoxSign);		
		comboBoxPanel.add(specificBenSearch);
		
		

		JScrollPane comboBoxScroll = new JScrollPane(comboBoxPanel);
		comboBoxScroll.setBorder(null);
		comboBoxScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
		comboBoxScroll.getHorizontalScrollBar().setPreferredSize(new Dimension(0,14));
		
		
		specificSearchBenPanel = new JPanel();
		specificSearchBenPanel.setLayout(new BorderLayout(0, 0));
		specificSearchBenPanel.add(comboBoxScroll, BorderLayout.NORTH);
		specificSearchBenPanel.add(specificSearchOptionsBenPanel, BorderLayout.CENTER);
		
		
		searchBenPanel.setLayout(new BorderLayout(0, 0));
		searchBenPanel.add(generalSearchBenPanel, BorderLayout.NORTH);
		searchBenPanel.add(specificSearchBenPanel, BorderLayout.CENTER);
		searchBenPanel.setBorder(new LineBorder(Color.black));
	}
	
	
	
	private boolean addPayment(double amount,int apartId, Timestamp date)
	{
		return addPayment(amount,apartId, date, true);
	}

	
	private boolean addPayment(double amount,int apartId, Timestamp date, boolean addResult)
	{
		int res = ctrRentalPay.insertPayment(date, amount, apartId);
		
		if(res == -1)
		{
			setError("Contract missing for apartment id: "+apartId);
			
			Object[] oneR = new Object[tableRentalHeader.length];
			int i=0;
			oneR[i++] = -1;
			oneR[i++] = date;
			oneR[i++] = amount;
			oneR[i++] = apartId;
			oneR[i++] = -1;
			
			if(addResult) failedPayments.add(oneR);
			return false;
		}
		else 
			if(res==-2)
			{
				setError("The payment for apartment id: "+apartId+" was already submitted to database.");
				return false;
			}
			
		
		return true;
	}
	
	
	JLabel ffTotalAmount;
	
	private void initComponents()
	{
		ffTotalAmount = new JLabel("0.00");
		ffTotalAmount.setFont(new Font("Verdana", Font.PLAIN, 13));
		
		initComponents_Rental();
		initComponents_Ben();
		
		Font detailsFont = new Font("verdana", Font.BOLD, 20);
		
		JLabel lblRental = new JLabel("Rental Payments");
		lblRental.setFont(detailsFont);
		
		JButton uploadRentalPayments = new JButton("Upload CSV");
		uploadRentalPayments.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) 
			{
				JFileChooser chooser = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter( "CSV Files (.csv)", "csv");
				chooser.setFileFilter(filter);
				Component parent = new JPanel();
				
				int returnVal = chooser.showOpenDialog(parent);
				
				if(returnVal == JFileChooser.APPROVE_OPTION) 
				{
					try{
						BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile().getPath()));
						String line;
					    	   
						SimpleDateFormat sDateFormat = new SimpleDateFormat("dd.MM.yyyy");
				    	
						
				    	while ((line = br.readLine()) != null) 
				    	{
				    		line = line.replaceAll("\"", "");
				    		
				    		String[] values = line.split(",");
				    		
				    		try{
				    			Timestamp dateS = new Timestamp(sDateFormat.parse(values[0]).getTime());
				    			int apartmentID = Integer.parseInt(values[1]);
				    			double amount = Double.parseDouble(values[2]);
				    			addPayment(amount,apartmentID,dateS);
				    		}
				    		catch(Exception ex){ }
				    	}
				    	
				    	br.close();
					}
					catch(Exception ex){
						setError("Failed to read the CSV file. Try again.");
						ex.printStackTrace();
					}
					
					
					makeTabelRental();
				}
			}
		});
		
		
		
		
		JPanel rentalDetails = new JPanel();
		
		GroupLayout gl_rentalDetails = new GroupLayout(rentalDetails);
		gl_rentalDetails.setHorizontalGroup(
			gl_rentalDetails.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_rentalDetails.createSequentialGroup()
					.addContainerGap()
					.addComponent(uploadRentalPayments)
					.addGap(61)
					.addComponent(lblRental))
		);
		gl_rentalDetails.setVerticalGroup(
			gl_rentalDetails.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_rentalDetails.createSequentialGroup()
					.addGap(5)
					.addGroup(gl_rentalDetails.createParallelGroup(Alignment.BASELINE)
						.addComponent(uploadRentalPayments)
						.addComponent(lblRental))
					.addGap(14))
		);
		rentalDetails.setLayout(gl_rentalDetails);
		
		
		
		
		JLabel lblBen = new JLabel("Beneficiary Payments");
		lblBen.setFont(detailsFont);
		
		JPanel benDetails = new JPanel();
		
		
		
		JButton btnPayMonth = new JButton("Pay for "+(getMonth()+1)+"."+getYear());
		btnPayMonth.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ctrBenPay.payBeneficiariesThisMonth())
				{
					makeTabelBen();
				}
				else
				{
					setError("The beneficiaries were already paid this month!");
				}
			}
		});
		
		mainPanel = new JPanel();
		
		JLabel lblNewLabel = new JLabel("Total: R");
		lblNewLabel.setFont(new Font("Verdana", Font.PLAIN, 13));
		
		
		
		GroupLayout gl_mainPanel = new GroupLayout(mainPanel);
		gl_mainPanel.setHorizontalGroup(
			gl_mainPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addComponent(searchRentalPanel, GroupLayout.PREFERRED_SIZE, 508, Short.MAX_VALUE)
					.addComponent(searchBenPanel, GroupLayout.PREFERRED_SIZE, 509, Short.MAX_VALUE))
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addComponent(rentalDetails, GroupLayout.PREFERRED_SIZE, 503, Short.MAX_VALUE)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(benDetails, GroupLayout.PREFERRED_SIZE, 514, Short.MAX_VALUE)
						.addGroup(gl_mainPanel.createSequentialGroup()
							.addGap(108)
							.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(ffTotalAmount, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
							.addContainerGap())))
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addComponent(tableRentalPanel, GroupLayout.PREFERRED_SIZE, 508, Short.MAX_VALUE)
					.addComponent(tableBenPanel, GroupLayout.PREFERRED_SIZE, 509, Short.MAX_VALUE))
		);
		gl_mainPanel.setVerticalGroup(
			gl_mainPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(searchRentalPanel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
						.addComponent(searchBenPanel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(rentalDetails, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_mainPanel.createSequentialGroup()
							.addComponent(benDetails, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblNewLabel)
								.addComponent(ffTotalAmount))))
					.addGap(7)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(tableBenPanel, GroupLayout.PREFERRED_SIZE, 314, Short.MAX_VALUE)
						.addComponent(tableRentalPanel, GroupLayout.PREFERRED_SIZE, 314, Short.MAX_VALUE)))
		);
		
		
		GroupLayout gl_benDetails = new GroupLayout(benDetails);
		gl_benDetails.setHorizontalGroup(
			gl_benDetails.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_benDetails.createSequentialGroup()
					.addGap(10)
					.addComponent(btnPayMonth)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(lblBen))
		);
		gl_benDetails.setVerticalGroup(
			gl_benDetails.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_benDetails.createSequentialGroup()
					.addGap(5)
					.addGroup(gl_benDetails.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnPayMonth)
						.addComponent(lblBen)))
		);
		benDetails.setLayout(gl_benDetails);
		
		
		mainPanel.setLayout(gl_mainPanel);
	}
}